package com.cars.nfp.service;

import com.cars.nfp.dto.LoginInfoDTO;
import com.cars.nfp.dto.LogoutDTO;
import com.cars.nfp.feign.UserAppClient;
import com.cars.util.global.GlobalReturnCode;
import com.cars.util.json.JsonResult;
import com.cars.util.json.JsonResultUtil;
import com.cars.util.jwt.JwtResult;
import com.cars.util.jwt.JwtUtil;
import com.crl.redis.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cars.nfp.token.Token;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户登录操作
 * <p>
 * 获取用户ROLE/AUTH/TOKEN/REFRESH_TOKEN
 *
 * @author 宋长军
 * @date 2019/8/16 9:09
 */
@Service
public class LoginService {

    @Autowired
    private UserAppClient userAppClient;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AuthRedisService authRedisService;

    /**
     * 根据用户名、密码、系统标识获取token信息
     *
     * @param loginInfoDTO 用户名 密码 验证码
     * @return 登录返回信息
     */
    public JsonResult login(LoginInfoDTO loginInfoDTO) {

        // 验证用户信息
        JsonResult loginResult = userAppClient.login(loginInfoDTO);
        // 用户信息验证成功
        if (GlobalReturnCode.OK.getReturnCode().equals(loginResult.getReturnCode())) {

            String username = loginInfoDTO.getUsername();
            // 获取token信息
            Token token = tokenService.getTokenByPass(username);
            Map<String, Object> resultData = (Map<String, Object>) loginResult.getData();

            // roleList
            List<String> roleList = (List<String>) resultData.get("roles");
            // recoureseList
            List<String> resourceList = (List<String>) resultData.get("resources");

            // 存储<username, resourceList>
            authRedisService.saveUserAuth(username, resourceList);
            // 存储<username, accessToken>
            authRedisService.saveUserAccessToken(username, JwtUtil.parseJWT(token.getAccessToken()).getToken());

            // 返回结果
            Map<String, Object> map = new HashMap<>(3);
            map.put("accessToken", token.getAccessToken());
            map.put("refreshToken", token.getRefreshToken());
            map.put("roleList", roleList);
            map.put("userId", resultData.get("userId"));
            return JsonResultUtil.ok(map);
        }

        // 用户信息验证失败
        else {
            return loginResult;
        }
    }

    /**
     * 用户登出操作
     *
     * @param logoutDTO 用户名
     * @return 退出结果
     */
    public JsonResult logout(LogoutDTO logoutDTO) {

        JwtResult jwtResult = JwtUtil.parseJWT(logoutDTO.getToken());
        if (jwtResult.isValid()) {

            String username = jwtResult.getOwner();
            // 删除<username, resourceList>
            authRedisService.deleteKey(RedisKey.HGP_AUTHORIZED_URL, username);
            // 删除<username, accessToken>
            authRedisService.deleteKey(RedisKey.HGP_USER_ACCESSTOKEN, username);
            return JsonResultUtil.ok();
        } else {

            return JsonResultUtil.error("登出失败！");
        }
    }
}
